﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Dynamic;
using System.Web.Mvc;
using System.Xml.Linq;
using Xenta.Attributes;
using Xenta.Utils;

namespace Xenta.Web.Controllers
{
    public sealed class AccountController : ExtController
    {
        #region GET/POST Actions

        [HttpGet]
        public ActionResult Show(int id)
        {
            var m = Svc.ProcessOperation("GetAccountWithProfiles", new
            {
                EntityID = id
            }, new
            {
                DisclosureLevel = "Entire"
            });
            if(m == null)
                return HttpNotFound();
            return View(m);
        }

        [HttpGet, PersistState, Authenticate]
        public ActionResult Init()
        {
            string attrKey = Par.In("WebPortal").Of("Registration").Name("Complete");
            if(!Svc.Attribute(attrKey, false))
            {
                try
                {
                    if(Svc.ForumMember == null)
                    {
                        Svc.ProcessOperation("CreateForumMember", new
                        {
                            AccountID = JDM.Int32(Svc.Account.EntityID),
                            AvatarFileID = 0,
                            Signature = String.Empty,
                            Flags = "Active"
                        });
                    }
                    if(Svc.FileOwner == null)
                    {
                        Svc.ProcessOperation("CreateFileOwner", new
                        {
                            AccountID = JDM.Int32(Svc.Account.EntityID),
                            Quota = Svc.Config<Int64>(Par.In("Core").Of("FileOwnerEntity").Name("DefaultQuota")),
                            Flags = "Active"
                        });
                    }
                    if(Svc.Customer == null)
                    {
                        Svc.ProcessOperation("CreateCustomer", new
                        {
                            AccountID = JDM.Int32(Svc.Account.EntityID),
                            Flags = "Active"
                        });
                    }
                    Svc.ProcessOperation("SetAccountAttribute", new
                    {
                        HolderID = JDM.Int32(Svc.Account.EntityID),
                        Key = attrKey,
                        Value = true
                    });
                }
                catch(Exception ex)
                {
                    Trace.TraceError(ex.Message);
                    return RedirectToAction(Loc.Act("SignOut").Ctrl("Access").Localized());
                }
            }
            return RedirectToAction(Loc.Act("Home").Ctrl("Static").Localized());
        }

        [HttpGet, RestoreState, Authenticate]
        public ActionResult Prof()
        {
            return View("Profile");
        }

        [HttpPost, PersistState, Authenticate]
        public ActionResult Prof(string fullName,
            string shortBio,
            string forumSignature,
            int avatarFileID)
        {
            try
            {
                Svc.ProcessOperation("SetAccountAttribute", new
                {
                    HolderID = JDM.Int32(Svc.Account.EntityID),
                    Key = Par.In("WebPortal").Of("Profile")
                        .Name("FullName").ToString(),
                    Value = fullName
                });
                Svc.ProcessOperation("SetAccountAttribute", new
                {
                    HolderID = JDM.Int32(Svc.Account.EntityID),
                    Key = Par.In("WebPortal").Of("Profile")
                        .Name("ShortBio").ToString(),
                    Value = shortBio
                });
                Svc.ProcessOperation("UpdateForumMember", new
                {
                    EntityID = JDM.Int32(Svc.ForumMember.EntityID),
                    AvatarFileID = avatarFileID,
                    Signature = forumSignature,
                    Flags = JDM.String(Svc.ForumMember.Flags)
                });
            }
            catch(Exception ex)
            {
                ModelState.AddModelError("API", ex);
            }
            return RedirectToAction(Loc.Act("Prof").Localized());
        }

        [HttpGet, RestoreState, Authenticate]
        public ActionResult Settings()
        {
            return View();
        }

        [HttpPost, PersistState, Authenticate]
        public ActionResult Password(string password)
        {
            try
            {
                Svc.ProcessOperation("ChangeAccountPassword", new
                {
                    EntityID = JDM.Int32(Svc.Account.EntityID),
                    Password = password,
                    SendNotification = true
                });
            }
            catch(Exception ex)
            {
                ModelState.AddModelError("API", ex);
            }
            return RedirectToAction(Loc.Act("Settings").Localized());
        }

        [HttpPost, PersistState, Authenticate]
        public ActionResult Preferences(int localizationProfileID, int historySize)
        {
            try
            {
                Svc.ProcessOperation("SetAccountAttribute", new
                {
                    HolderID = JDM.Int32(Svc.Account.EntityID),
                    Key = Par.In("WebPortal").Of("Preferences")
                        .Name("HistorySize").ToString(),
                    Value = historySize
                });
                Svc.ProcessOperation("UpdateAccount", new
                {
                    EntityID = JDM.Int32(Svc.Account.EntityID),
                    LocalizationProfileID = localizationProfileID,
                    Email = JDM.String(Svc.Account.Email),
                    Username = JDM.String(Svc.Account.Username),
                    Flags = JDM.String(Svc.Account.Flags)
                });
            }
            catch(Exception ex)
            {
                ModelState.AddModelError("API", ex);
            }
            return RedirectToAction(Loc.Act("Settings").Localized());
        }

        #endregion

        #region Child Actions

        [ChildActionOnly]
        public ActionResult _Overview(int id)
        {
            var m = Svc.ProcessOperation("GetAccountWithProfiles", new
            {
                EntityID = id
            }, new
            {
                DisclosureLevel = "Entire"
            });
            if(m == null)
                return HttpNotFound();
            return View(m);
        }

        [ChildActionOnly, ActionCache("short", true, VaryByParam = "id", VaryByCustom = "locale")]
        public ActionResult _Activity(int id)
        {
            dynamic m = new ExpandoObject();
            long rptElapsedTime = 0;
            string rptMimeType = String.Empty;

            m.Error = String.Empty;
            m.Data = null;
            m.ElapsedTime = 0;
            try
            {
                using(var rptData = Svc.BuildReport("ActivityReport",
                    new Dictionary<String, String>
                    {
                        {"accountID", id.ToString()},
                        {"languageID", JDM.String(Svc.Localization.Language.EntityID)},
                    },
                    out rptMimeType,
                    out rptElapsedTime))
                {
                    m.Data = XElement.Load(rptData);
                }
            }
            catch(Exception ex)
            {
                m.Error = ex.ToString();
            }
            m.ElapsedTime = rptElapsedTime;

            return PartialView(m);
        }

        #endregion
    }
}
